﻿using JinYuan.Helper;
using JinYuan.VirtualDataLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace LargeSquareOne
{
    public partial class FrmMonitor : Form
    {
        private static object uiLock = new object();
        /// <summary>
        /// 窗体实例
        /// </summary>
        private static FrmMonitor _instance;
        public static FrmMonitor Instance
        {
            get
            {
                lock (uiLock)
                {
                    if (_instance == null)
                    {
                        _instance = new FrmMonitor();
                    }
                    return _instance;
                }
            }
        }

        public FrmMonitor()
        {
            InitializeComponent();

            ////设置控件样式，去除缓冲
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.Selectable, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);

            #region 字体加载
            // 加载字体文件
            font.AddFontFile(Environment.CurrentDirectory + "\\Assts\\Fonts\\FZY4JW.ttf");
            //定义成新的字体对象
            FontFamily myFontFamily = new FontFamily(font.Families[0].Name, font);
            myFont = new Font(myFontFamily, 20, FontStyle.Bold);
            //将字体显示到控件
            //longTitleStyle21.Font = myFont;
            #endregion

            this.FormClosing += (sender, e) =>
            {
                this.m_RefreshTimer?.Dispose();
                //this.m_RefreshTimerWeeding?.Dispose();
            };
        }

        #region 静止闪烁
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0014) // 禁掉清除背景消息
                return;
            base.WndProc(ref m);
        }
        #endregion

        PrivateFontCollection font = new PrivateFontCollection();
        Font myFont;

        /// <summary>
        /// 按钮状态委托
        /// </summary>
        /// <param name="time"></param>
        private delegate void ShowChatHandler();


        //定时存储定时器
        private System.Threading.Timer m_RefreshTimer;

        private void FrmMonitor_Load(object sender, EventArgs e)
        {
            SetChart();
            RefreshXiaoLvData();
            RefreshChatTop10AlarmData();

            m_RefreshTimer = new System.Threading.Timer(TimerWork_Elapsed, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
            StartTimer(m_RefreshTimer);//开启刷新


        }

        /// <summary>
        /// 开启定时器
        /// </summary>
        /// <param name="timer"></param>
        private void StartTimer(System.Threading.Timer timer)
        {
            timer?.Change(TimeSpan.Zero, Timeout.InfiniteTimeSpan);
        }

        #region 定时刷新状态
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        private void TimerWork_Elapsed(object sender)
        {
            try
            {
                using (new TimerReset(m_RefreshTimer, 2000))
                {
                    Refish12ProdQty();
                    RefreshXiaoLvData();//设备综合效率
                    RefreshChatTop10AlarmData();
                    RefreshChatNGData();
                }
            }
            catch (Exception ex)
            {
                CommonMethods.AddLog(true, "定时刷新异常：" + ex.Message);
            }
        }


        #endregion

        #region 刷新12小时产能

        private void SetChart()
        {
            #region 24小时统计


            Chart12HourTotal.Series.Clear();
            //chart12Hour.Titles.Clear();

            Chart12HourTotal.ChartAreas[0].AxisY.Minimum = 0;
            Chart12HourTotal.ChartAreas[0].AxisY.Maximum = 2000;
            ChartHelper.AddSeries(Chart12HourTotal, "投入", SeriesChartType.Column, ChartValueType.Auto, MarkerStyle.Diamond, 8, Color.DarkTurquoise, Color.Aqua, "", false, true);
            ChartHelper.AddSeries(Chart12HourTotal, "产出", SeriesChartType.Column, ChartValueType.Auto, MarkerStyle.Diamond, 8, Color.PaleGoldenrod, Color.PaleGoldenrod, "", false, true);
            ChartHelper.AddSeries(Chart12HourTotal, "优率", SeriesChartType.Spline, ChartValueType.String, MarkerStyle.Circle, 8, Color.Lime, Color.Lime, "#VAL{P}", true, true);

            //JinYuan.Helper.ChartHelper.SetTitle(chart12Hour, "当日每1小时投入与产出", new Font("微软雅黑", 12), Docking.Top, Color.White);
            ChartHelper.SetStyle(Chart12HourTotal, Color.Transparent, Color.White);
            ChartHelper.SetLegend(Chart12HourTotal, Docking.Top, StringAlignment.Center, Color.Transparent, Color.White);
            ChartHelper.SetXY(Chart12HourTotal, "时间", "数值", 0, StringAlignment.Center, Color.White, Color.White, AxisArrowStyle.None, 1, true);
            ChartHelper.SetMajorGrid(Chart12HourTotal, Color.Transparent, 20, 2);
            #endregion
        }


        /// <summary>
        /// 刷新12小时产能
        /// </summary>
        /// 

        private void Refish12ProdQty()
        {
            Task.Run(() =>
            {
                try
                {
                    this.BeginInvoke((EventHandler)delegate
                    {
                        ucPanel12Hour.Title = string.Format($"当前({CommonMethods.strClass})产能");
                        if (CommonMethods.Lst_Prod12HourData != null && CommonMethods.Lst_Prod12HourData.Count > 0)
                        {
                            Chart12HourTotal.ChartAreas[0].AxisY.Minimum = 0;
                            var maxValue = CommonMethods.Lst_Prod12HourData.Max(x => x.ProdIn);
                            Chart12HourTotal.ChartAreas[0].AxisY.Maximum = (int)maxValue + 1500;

                            var x1 = CommonMethods.Lst_Prod12HourData.Select(c => c.DisplayTime).ToList();
                            var y1 = CommonMethods.Lst_Prod12HourData.Select(c => c.ProdIn).ToList();
                            var y2 = CommonMethods.Lst_Prod12HourData.Select(c => c.ProdOut).ToList();
                            var y3 = CommonMethods.Lst_Prod12HourData.Select(c => c.OKRatio).ToList();

                            //绑定数据
                            Chart12HourTotal.Series[0].Points.DataBindXY(x1, y1);
                            Chart12HourTotal.Series[1].Points.DataBindXY(x1, y2);
                            Chart12HourTotal.Series[2].Points.DataBindXY(x1, y3);
                        }
                    });
                }
                catch
                {

                }
            });
        }
        #endregion

        #region 设备综合效率
        private void RefreshXiaoLvData()
        {
            int TotalQty = CommonMethods.TotalQty;
            int ProOKQty = CommonMethods.ProOKQty;
            int PPM = CommonMethods.Ppm;

            string Factory_code = CommonMethods.mesConfig.siteCode;
            string line_No = CommonMethods.mesConfig.lineCode;
            string Eqp_code = CommonMethods.mesConfig.equipNum;
            double UtilizationRate = Convert.ToDouble(CommonMethods.JiaDL) * 100;
            double YieldRate = 0;
            bool flag = TotalQty == 0L;
            if (!flag)
            {
                YieldRate = Convert.ToDouble((Convert.ToDouble(ProOKQty) / Convert.ToDouble(TotalQty) * 100.0).ToString("f2"));
            }

            this.Invoke((EventHandler)delegate
            {
                #region 除尘风速
                //if (CommonMethods.AntiDustAirSpeed[0] > 0.001f)
                //{
                //    ucFengSu1.CurrentValue = CommonMethods.AntiDustAirSpeed[0];
                //}
                //else
                //{
                //    ucFengSu1.CurrentValue = 0;
                //}
                #endregion
                titleModeName.Title = CommonMethods.mesConfig.ModelName;
                titleFactory_code.Title = Factory_code;
                titleLine_No.Title = line_No;
                titleEqp_code.Title = Eqp_code;
                proUtilizationRate.FloatValue = (float)UtilizationRate;
                proPPM.IntValue = PPM;
                proOKQty.IntValue = ProOKQty;
                proOKRatio.Value = YieldRate.ToString() == "NaN" ? 0 : YieldRate;
                proTotalQty.TotalValue = TotalQty;

                if (CommonMethods.PlcOpenAndRunTime != null && CommonMethods.PlcOpenAndRunTime.Count > 0)
                {
                    titleStartTime.Title = $"{CommonMethods.PlcOpenAndRunTime[0]}:{CommonMethods.PlcOpenAndRunTime[1]}:{CommonMethods.PlcOpenAndRunTime[2]}";
                    titleRunTime.Title = $"{CommonMethods.PlcOpenAndRunTime[3]}:{CommonMethods.PlcOpenAndRunTime[4]}:{CommonMethods.PlcOpenAndRunTime[5]}";
                }

                if (CommonMethods.listElectricEnergy != null && CommonMethods.listElectricEnergy.Count > 0)
                {
                    this.ucElectricityMeterV1.ElectricEnergy = CommonMethods.listElectricEnergy[0];
                    //this.ucElectricityMeterV2.ElectricEnergy = CommonMethods.listElectricEnergy[1];
                }
            });

        }
        #endregion

        #region 报警Top10信息刷新
        private void RefreshChatTop10AlarmData()
        {
            this.BeginInvoke((EventHandler)delegate
            {
                if (CommonMethods.Lst_AlarmTop10_Qty != null && CommonMethods.Lst_AlarmTop10_Qty.Count > 0)
                {
                    chartAlarmData.Series.Clear();
                    chartAlarmData.Titles.Clear();
                    chartAlarmData.ChartAreas[0].AxisY.Minimum = 0;
                    var maxValue1 = CommonMethods.Lst_AlarmTop10_Qty.Max(x => x.DataCount);
                    chartAlarmData.ChartAreas[0].AxisY.Maximum = (int)maxValue1 + 20;
                    foreach (var item in CommonMethods.Lst_AlarmTop10_Qty)
                    {
                        ChartHelper.AddSeries(chartAlarmData, item.DataType, SeriesChartType.Column, ChartValueType.Auto, MarkerStyle.Diamond, 4, Color.DarkTurquoise, Color.White, "", false, true);
                    }
                    ChartHelper.SetTitle(chartAlarmData, "报警TOP10", new Font("微软雅黑", 12), Docking.Top, Color.White);
                    ChartHelper.SetStyle(chartAlarmData, Color.Transparent, Color.White);
                    ChartHelper.SetLegend(chartAlarmData, Docking.Top, StringAlignment.Center, Color.Transparent, Color.White);
                    ChartHelper.SetXY(chartAlarmData, "报警项", "次数", -45, StringAlignment.Center, Color.White, Color.White, AxisArrowStyle.None, 1, false);
                    ChartHelper.SetMajorGrid(chartAlarmData, Color.Transparent, 20, 2);
                    //不良类型统计
                    List<string> xData1 = CommonMethods.Lst_AlarmTop10_Qty.Select(c => c.DataType).ToList();
                    List<int> yData1 = CommonMethods.Lst_AlarmTop10_Qty.Select(c => c.DataCount).ToList();

                    chartAlarmData.Series[0].Points.DataBindXY(xData1, yData1);

                }
                else
                {
                    chartAlarmData.Series.Clear();
                    chartAlarmData.Titles.Clear();
                    chartAlarmData.ChartAreas[0].AxisY.Minimum = 0;
                }

            });
        }

        #endregion

        #region 不良信息刷新
        private void RefreshChatNGData()
        {
            this.BeginInvoke((EventHandler)delegate
            {
                if (CommonMethods.Lst_DefectTypeQty != null && CommonMethods.Lst_DefectTypeQty.Count > 0)
                {
                    chartNgShow.Series.Clear();
                    chartNgShow.Titles.Clear();
                    chartNgShow.ChartAreas[0].AxisY.Minimum = 0;
                    var maxValue = CommonMethods.Lst_DefectTypeQty.Max(x => x.DataCount);
                    chartNgShow.ChartAreas[0].AxisY.Maximum = (int)maxValue + 100;
                    foreach (var item in CommonMethods.Lst_DefectTypeQty)
                    {
                        ChartHelper.AddSeries(chartNgShow, item.DataType, SeriesChartType.Column, ChartValueType.Auto, MarkerStyle.Diamond, 4, Color.Red, Color.White, "", false, true);
                    }
                    ChartHelper.SetTitle(chartNgShow, "各不良项", new Font("微软雅黑", 12), Docking.Top, Color.White);
                    ChartHelper.SetStyle(chartNgShow, Color.Transparent, Color.White);
                    ChartHelper.SetLegend(chartNgShow, Docking.Top, StringAlignment.Center, Color.Transparent, Color.White);
                    ChartHelper.SetXY(chartNgShow, "项名", "数值", 0, StringAlignment.Center, Color.White, Color.White, AxisArrowStyle.None, 1, false);
                    ChartHelper.SetMajorGrid(chartNgShow, Color.Transparent, 1, 1);

                    //不良类型统计
                    List<string> xData = CommonMethods.Lst_DefectTypeQty.Select(c => c.DataType).ToList();
                    List<int> yData = CommonMethods.Lst_DefectTypeQty.Select(c => c.DataCount).ToList();


                    chartNgShow.Series[0].Points.DataBindXY(xData, yData);

                }
            });
        }


        #endregion

        private void titleStartTime_Load(object sender, EventArgs e)
        {

        }
    }
}